﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using K3R.Generics;

namespace K3R.Data {
	public static class Extension {
		// Generic
		public static T DBValueOrDefault<T>(this object item, T defValue) {
			return (item != DBNull.Value ? (T)item : defValue);
		}

		public static T DBValueOrDefault<T>(this DbParameter item, T defValue) {
			return (item.Value != DBNull.Value ? (T)item.Value : defValue);
		}

		public static T DBValueOrDefault<T>(this object item) {
			return item.DBValueOrDefault(default(T));
		}

		public static T DBValueOrDefault<T>(this DbParameter item) {
			return item.DBValueOrDefault(default(T));
		}

		public static List<string> GetFieldNames(this DbDataReader dr) {
			List<string> fieldNames = new List<string>();
			for (int i = 0; i < dr.FieldCount; i++)
				fieldNames.Add(dr.GetName(i));

			return fieldNames;
		}

		public static bool FieldExists(this DbDataReader dr, string name) {
			return dr.GetFieldNames().Contains(name);
		}

		public static List<T> ToList<T>(this DbDataReader dr, T defValue) {
			List<T> list = new List<T>();
			while (dr.Read())
				list.Add(dr[0].DBValueOrDefault(defValue));
			return list;
		}

		public static List<T> ToList<T>(this DbDataReader dr) {
			return dr.ToList(default(T));
		}

		public static Dictionary<K, V> ToDictionary<K, V>(this DbDataReader dr) {
			Dictionary<K, V> list = new Dictionary<K, V>();
			while (dr.Read())
				list.Add(dr[0].DBValueOrDefault<K>(), dr[1].DBValueOrDefault<V>());
			return list;
		}

		public static List<SerializableKeyValuePair<K, V>> ToSerializableKeyValuePairList<K, V>(this DbDataReader dr) {
			var list = new List<SerializableKeyValuePair<K, V>>();
			while (dr.Read())
				list.Add(new SerializableKeyValuePair<K, V> {
					Key = dr[0].DBValueOrDefault<K>(),
					Value = dr[1].DBValueOrDefault<V>()
				});
			return list;
		}
	}
}
